package com.taobao.fanli.service;

import com.taobao.fanli.dao.mapper.ActivityMapper;
import com.taobao.fanli.dao.mapper.RedpackMapper;
import com.taobao.fanli.dao.mapper.RuleMapper;
import com.taobao.fanli.dao.model.*;
import com.taobao.fanli.postbean.RedpackInitBean;
import com.taobao.fanli.utils.DateUtil;
import com.taobao.fanli.vo.Login;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class RedPackService {

    private static final Logger logger = LoggerFactory.getLogger(RedPackService.class);

    @Resource
    private RuleMapper ruleMapper;
    @Resource
    private RedpackMapper redpackMapper;
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private UserService userService;
    @Resource
    private TransactionService transactionService;

    //初始化
    public void init(RedpackInitBean redpackInitBean) throws RuntimeException{
        Boolean isExist = userService.checkUser(redpackInitBean.getUserId());
        if(!isExist){
            throw  new RuntimeException("用户没有注册，请注册");
        }

        List<Activity> activitys = activityMapper.selectByType(redpackInitBean.getType());
        for (Activity activity : activitys){
            Date endTime = activity.getEndTime();
            Date date = new Date();
            if( endTime!= null && endTime.getTime() < date.getTime()){
                throw new RuntimeException("活动已结束");
            }

            List<Rule> rules = ruleMapper.getRuleByActivityId(redpackInitBean.getType());
            for (Rule rule : rules){
                Redpack redpack = redpackMapper.checkUserRedpackIsExist(rule.getId(), redpackInitBean.getUserId());
                if(redpack == null){
                    //红包初始化
                    redpack = new Redpack();
                    redpack.setUserId(redpackInitBean.getUserId());
                    redpack.setMoney(rule.getRedpack());
                    redpack.setRuleId(rule.getId());
                    redpack.setStatus(0);
                    Date day = DateUtil.getDay(new Date(), rule.getExpressTime());
                    redpack.setExpireTime(day);
                    redpack.setCreateAt(new Date());
                    redpackMapper.insert(redpack);
                    //流水帐存储
                    transactionService.insertOne(redpackInitBean.getUserId(), rule.getRedpack(),
                            TransactionService.FROZENMONEYSTATE, TransactionService.REDPACKFROM, null);
                }
            }
        }
        //用户金额计算
//        userService.updateReceiceAndFrozen(redpackInitBean.getUserId());
    }

    //查询可领取红包列表
    public List<ReceiveRedpack> queryList(Login userByCookie) {
        Date now = new Date();
        List<ReceiveRedpack> userRedpackList = redpackMapper.getUserRedpackList(userByCookie.getId());
        if(userRedpackList != null && !userRedpackList.isEmpty()){
            for (ReceiveRedpack receiveRedpack : userRedpackList){
                if(now.getTime() > receiveRedpack.getExpireTime().getTime() && (receiveRedpack.getStatus() == 0 || receiveRedpack.getStatus() == 1)){
                    receiveRedpack.setStatus(3);
                    Redpack redpack = new Redpack();
                    redpack.setId(receiveRedpack.getId());
                    redpack.setStatus(3);
                    redpackMapper.updateByPrimaryKeySelective(redpack);
                }
            }
        }
        return userRedpackList;
    }

    //更新红包为已领取
    public void updateReceiveRedpack(Login userByCookie, Integer redpackId) {
        Redpack redpack = redpackMapper.selectByPrimaryKey(redpackId);
        if(redpack == null){
            throw new RuntimeException("没有此红包");
        }
        if(!redpack.getUserId().equals(userByCookie.getId())){
            throw new RuntimeException("红包不是你的，别乱领取!!!");
        }
        if(redpack.getStatus() == 0){
            throw new RuntimeException("暂时还不能领取红包");
        }
        if(redpack.getStatus() == 2){
            throw new RuntimeException("用户已领取红包，请注意查收");
        }
        redpack.setStatus(2);
        redpackMapper.updateByPrimaryKey(redpack);

        //流水帐存储
        BigDecimal money = redpack.getMoney();
        //减冻结金额
        transactionService.insertOne(userByCookie.getId(), money.negate(),
                TransactionService.FROZENMONEYSTATE, TransactionService.REDPACKFROM, null);
        //加可领取金额
        transactionService.insertOne(userByCookie.getId(), money,
                TransactionService.RECEIVEMONEYSTATE, TransactionService.REDPACKFROM, null);
        //用户金额计算
        userService.updateReceiceAndFrozen(userByCookie.getId());
    }
}
